﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EnvironmentValueSetter
{
    public class EnvironmentVariableHander
    {
        public EnvironmentVariableTarget Target { get; private set; }

        public Dictionary<string, string> EnvironmentVariablesCache { get; private set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="target">Machine包含path和系统变量;User代表用户变量</param>
        public EnvironmentVariableHander(EnvironmentVariableTarget target)
        {
            Target = target;
        }


        /// <summary>
        /// 单例模式,获取环境变量
        /// </summary>
        /// <param name="GetFromCache"></param>
        /// <returns></returns>
        public Dictionary<string, string> GetEnvironmentVariablesCache(bool GetFromCache = true)
        {
            if (!GetFromCache || EnvironmentVariablesCache == null)
            {
                EnvironmentVariablesCache = GetAllEnvironmentVariable();
            }
            return EnvironmentVariablesCache;
        }




        /// <summary>
        /// 遍历获取变量字典
        /// </summary>
        /// <returns></returns>
        public virtual Dictionary<string, string> GetAllEnvironmentVariable()
        {
            var dit = new Dictionary<string, string>();
            var d2 = Environment.GetEnvironmentVariables(Target);
            var keys = d2.Keys;
            var temp = keys.GetEnumerator();
            for (int i = 0; i < d2.Count; i++)
            {
                temp.MoveNext();
                var key = temp.Current;
                dit.Add(key.ToString(), d2[key].ToString());
            }
            return dit;
        }


        /// <summary>
        /// 判断是否存在
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public virtual bool IsEnvironmentVariableExist(string key)
        {
            var dict = GetEnvironmentVariablesCache();
            return dict.ContainsKey(key);
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public virtual string Get(string key)
        {
            var dict = GetEnvironmentVariablesCache();
            if (dict.ContainsKey(key))
                return dict[key];
            return null;
        }

        /// <summary>
        /// 设置
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public virtual void Set(string key, string value)
        {
            Environment.SetEnvironmentVariable(key, value, Target);
        }

        /// <summary>
        /// 设置变量
        /// </summary>
        /// <param name="dictionary"></param>
        public virtual void Set(Dictionary<string, string> dictionary)
        {
            foreach (var item in dictionary)
            {
                Set(item.Key, item.Value);
            }
        }
        #region Path设置


        public virtual void ClearPath(List<string> ss)
        {
            string old = GetOldPath();
            System.IO.DirectoryInfo systemDirectory = new System.IO.DirectoryInfo(Environment.SystemDirectory);
            string systemWindwosDirectoryPath = systemDirectory.Parent.FullName;
            //Console.WriteLine("系统目录:" + systemWindwosDirectoryPath);
            //处理特殊的系统宏命令占位
            old = old.Replace(systemWindwosDirectoryPath, "%SYSTEMROOT%");
            var oldArray = old.Split(';');
            var l = oldArray.Except(ss);
            string targetAppen = string.Join(";", l.ToArray());
            foreach (var item in l)
            {
                Console.WriteLine(item);
            }
            return;
            Environment.SetEnvironmentVariable("Path", targetAppen, EnvironmentVariableTarget.Machine);
        }

        public virtual void SetPath(List<string> ss)
        {
            string old = GetOldPath();
            System.IO.DirectoryInfo systemDirectory = new System.IO.DirectoryInfo(Environment.SystemDirectory);
            string systemWindwosDirectoryPath = systemDirectory.Parent.FullName;
            //Console.WriteLine("系统目录:" + systemWindwosDirectoryPath);
            //处理特殊的系统宏命令占位
            old = old.Replace(systemWindwosDirectoryPath, "%SystemRoot%");
            var oldArray = old.Split(';');
            for (int i = 0; i < oldArray.Length; i++)
            {
                for (int j = 0; j < ss.Count; j++)
                {
                    if (ss[j].Equals(oldArray[i], StringComparison.InvariantCultureIgnoreCase))
                        ss.RemoveAt(j);
                }
            }
            string targetAppen = string.Join(";", ss.Where(o => !string.IsNullOrEmpty(o)).ToArray());         
            Environment.SetEnvironmentVariable("Path", old + ";" + targetAppen, Target);

        }

        private string GetOldPath()
        {
            if (Target != EnvironmentVariableTarget.Machine)
                Target = EnvironmentVariableTarget.Machine;
            string old = GetEnvironmentVariablesCache()["Path"];
            return old;
        }

        /// <summary>
        /// 输出旧的path值
        /// </summary>
        public static void OutPutOldPath()
        {

            var dit = new Dictionary<string, string>();
            var d2 = Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Machine);
            if (d2.Contains("Path"))
            {
                string oldPath = d2["Path"] as string;
                if (!string.IsNullOrEmpty(oldPath))
                {
                    string[] fuck = oldPath.Split(';');
                    Console.WriteLine("-------------------旧的path值如下---------------------------");
                    for (int i = 0; i < fuck.Length; i++)
                    {
                        Console.WriteLine(fuck[i]);
                    }
                    Console.WriteLine("-------------------旧的path值如上---------------------------");
                }
            }
        }
        #endregion


    }
}
